package com.abe.hello.base.config.database;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
public class DataSourceConfig {
	@Value("${spring.datasource.primary.url}")
	private String dbUrl1;

	@Value("${spring.datasource.primary.username}")
	private String username1;

	@Value("${spring.datasource.primary.password}")
	private String password1;

	@Value("${spring.datasource.secondary.url}")
	private String dbUrl2;
	
	@Value("${spring.datasource.secondary.username}")
	private String username2;

	@Value("${spring.datasource.secondary.password}")
	private String password2;

	@Value("${spring.datasource.driver-class-name}")
	private String driverClassName;

	@Bean(name = "primaryDataSource")
	@Qualifier("primaryDataSource")
	// @ConfigurationProperties(prefix = "spring.datasource.primary")
	public DataSource primaryDataSource() {

		return getDataSource(username1, password1, dbUrl1);
	}

	@Bean(name = "secondaryDataSource")
	@Qualifier("secondaryDataSource")
	@Primary
	// @ConfigurationProperties(prefix = "spring.datasource.secondary")
	public DataSource secondaryDataSource() {
		return getDataSource(username2, password2, dbUrl2);
	}

	private DataSource getDataSource(String username, String password, String url) {
		return DataSourceBuilder.create().driverClassName(driverClassName).url(url).username(username)
				.password(password).build();
	}

	@Bean(name = "primaryJdbcTemplate")
	public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") DataSource dataSource) {
		return new JdbcTemplate(dataSource);
	}

	@Bean(name = "secondaryJdbcTemplate")
	public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") DataSource dataSource) {
		return new JdbcTemplate(dataSource);
	}
}
